﻿/// <reference path="msgesture.d.ts" />
/// <reference path="../../scripts/typings/knockout/knockout.d.ts" />
import ko = require("knockout");

class MsGesture {
    public static tryBindPointer(element, event) {
        // Process pointer.
        //  Attach first contact and track device.
        if (element.gesture.pointerType === null) {
            element.gesture.addPointer(event.pointerId);
            element.gesture.pointerType = event.pointerType;
        }
        // Attach subsequent contacts from same device.
        else if (event.pointerType === element.gesture.pointerType) {
            element.gesture.addPointer(event.pointerId);
        }
        // New gesture recognizer for new pointer type.
        else {
            var msGesture = new MSGesture();
            msGesture.target = event.target;
            event.target.gesture = msGesture;
            event.target.gesture.pointerType = event.pointerType;
            event.target.gesture.addPointer(event.pointerId);
        }
    }

    public static addGestureHandler(name) {
        ko.bindingHandlers['msGesture' + name] = {
            init: (element, valueAccessor) => {
                var msGesture = new MSGesture();
                msGesture.target = element;
                element.gesture = msGesture;
                element.gesture.pointerType = null;
                element.pointers = [];
            },
            update: (element, valueAccessor) => {
                element.addEventListener("pointerdown", (event) => { MsGesture.tryBindPointer(element, event); });
                if ('b_msGesture' + name in element) {
                    element.removeEventListener(element._msGestureChange);
                }
                element['b_msGesture' + name] = element.addEventListener("MSGesture" + name, function(event) {
                    valueAccessor()(event, this);
                });
            }
        }
    }

    public static create() {
        ["Start", "End", "Change", "Tap", "Hold"].map((value) => {
            MsGesture.addGestureHandler(value);
        });
    }
}

export = MsGesture